package com.dropdb.demo.service.impl;

import com.dropdb.demo.bean.Topic;
import com.dropdb.demo.bean.TopicExample;
import com.dropdb.demo.bean.vo.WXTopicVO;
import com.dropdb.demo.mapper.TopicMapper;
import com.dropdb.demo.service.TopicService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class TopicServiceImpl implements TopicService {
    @Autowired
    TopicMapper topicMapper;

    /**
     * 分页获取专题信息
     * @param page
     * @param size
     * @return
     */
    @Override
    public HashMap<String, Object> listTopics(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<WXTopicVO> topics = topicMapper.selectListOfTopicVO();
        PageInfo<WXTopicVO> info = new PageInfo<>(topics);
        long total = info.getTotal();
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", topics);
        map.put("count", total);
        return map;
    }


    /**
     * 获取该专题详细信息
     * @param id
     * @return
     */
    @Override
    public HashMap<String, Object> getTopicDetail(Integer id) {
        Topic topic = topicMapper.selectByPrimaryKey(id);
        HashMap<String, Object> map = new HashMap<>();
        // 防止逻辑删除
        if (topic.getDeleted()) topic = null;
        // 防止空指针异常
        if (topic == null) return null;
        map.put("topic", topic);
        map.put("goods", topic.getGoods());
        return map;
    }


    /**
     * 获取related topic
     * @return
     * @param id
     */
    @Override
    public List<Topic> getRelatedTopic(Integer id) {
        TopicExample example = new TopicExample();
        example.setOrderByClause("sort_order desc limit 4");
        example.createCriteria().andIdNotEqualTo(id).andDeletedEqualTo(false);
        List<Topic> topics = topicMapper.selectByExample(example);
        return topics;
    }
}
